package vip.ifmm.lehouse.file.service.api.impl;

import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.util.StringUtils;
import vip.ifmm.lehouse.common.dto.ServerResponse;
import vip.ifmm.lehouse.common.enums.status.FileStatus;
import vip.ifmm.lehouse.common.model.Enclosure;
import vip.ifmm.lehouse.common.util.CodeUtil;
import vip.ifmm.lehouse.file.service.api.EnclosureService;
import vip.ifmm.lehouse.file.service.api.FileService;
import vip.ifmm.lehouse.file.service.utils.UploaderUtil;

import javax.annotation.Resource;

/**
 * @author: mackyhuang
 * <p>email: mackyhuang@163.com <p>
 * <p>date: 2019/6/17 </p>
 * 文件上传，提供前端和后台接口
 */
@Service(owner = "mackyhuang",
        mock = "vip.ifmm.lehouse.file.service.api.mock.FileServiceMock")
public class FileServiceImpl implements FileService {

    @Resource
    private EnclosureService enclosureService;

    /**
     * 用于前端上传文件的 上传部分的服务
     * @param uniqueId
     * @param file
     * @param module
     * @param extension
     * @return
     */
    @Override
    public ServerResponse upload(String uniqueId, byte[] file, String module, String extension) {

        if (StringUtils.isEmpty(uniqueId)){
            return ServerResponse.response(FileStatus.UNI_CODE_EMPTY);
        } else if (file == null || file.length == 0){
            return ServerResponse.response(FileStatus.FILE_IS_EMPTY);
        } else if (module == null){
            return ServerResponse.response(FileStatus.MODULE_IS_EMPTY);
        } else if (extension == null){
            return ServerResponse.response(FileStatus.EXTENSION_IS_EMPTY);
        }
        String path = UploaderUtil.upload(uniqueId, file, module, extension);
        return ServerResponse.response(FileStatus.UPLOAD_SUCCESS, path);
    }

    @Override
    public ServerResponse uploadForBack(byte[] file, String module, String extension, String name, int size) {
        ServerResponse uploadResponse = null;
        Enclosure enclosure = null;
        if (file == null || file.length == 0){
            return ServerResponse.response(FileStatus.FILE_IS_EMPTY);
        }
        String uniqueId = CodeUtil.randomString(16);
        uploadResponse = upload(uniqueId, file, module, extension);
        if (uploadResponse.isSuccess()){
            enclosure = Enclosure.builder().enclosureName(name)
                    .enclosurePath(uploadResponse.getData().toString())
                    .enclosureSize(size)
                    .enclosureSuffix(extension).build();
            uploadResponse = enclosureService.saveEnclosureInfo(enclosure);
        }
        return uploadResponse;
    }
}
